/**
 * @author wangze
 * @date 2017-12-14 11:23.
 * reference 需要bootbox
 **/


;(function () {
    var exporter = {};

    exporter.API_KEY_NAME = 'api_key';

    exporter.getApiKey = function () {
        var api_Key = window.localStorage.getItem(exporter.API_KEY_NAME) || '';
        if (api_Key) {
            return api_Key;
        }
        return "";
    };
    exporter.getApiKeyUrl = function () {
        var api_Key = exporter.getApiKey();
        if (api_Key) {
            return '&' + exporter.API_KEY_NAME + '=' + api_Key;
        }
        return "";
    };

    //指定预处理参数选项的函数
    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
        var api_Key = exporter.getApiKey();
        if (api_Key) {
            options.headers = {};
            options.headers[exporter.API_KEY_NAME] = api_Key;

        }
    });


    var ajaxDefaultOpt = {
        async: true,
        url: '',
        dataType: 'json',
        type: 'post',
        cache: false
    };
    // var defaultDialogOpt = {
    //     message: '',
    //     closeButton: true,
    //     show: true,
    //     title: '',
    //     animate: true,
    //     className: ''
    // };

    var defaultEditDialogOpt = {
        message: '',
        closeButton: true,
        show: true,
        title: '',
        animate: true,
        className: 'my-modal',
        buttons: {
            ok: {
                label: "确定",
                className: 'btn-info',
                callback: function () {
                }
            },
            cancel: {
                label: "取消",
                className: 'btn-danger',
                callback: function () {
                }
            }
        }
    };


    var defaultDialgEvent = {
        init: function () {

        },
        success: function () {

        },
        fail: function () {

        }

    };


    //dialog
    exporter.dialog = {};
    //消息框，传入消息
    exporter.dialog.info = function (msg) {
        return layer.alert(msg, {
            skin: 'layui-layer-lan',
            closeBtn: 0,
            icon: 1,
            anim: 5 //动画类型
        });
    };

    //消息框，传入消息
    exporter.dialog.infoNoBtn = function (msg) {
        return layer.alert(msg, {
            skin: 'layui-layer-lan',
            closeBtn: 0,
            icon: 1,
            btn: [],
            anim: 5 //动画类型
        });
    };

    //消息框，传入消息
    exporter.dialog.warn = function (msg) {
        return layer.alert(msg, {
            skin: 'layui-layer-lan',
            closeBtn: 0,
            icon: 2,
            anim: 4 //动画类型
        });
    };

    /**
     * 自定页
     * @param opt
     */
    exporter.dialog.open = function (opt) {

        var defaultOptions = {
            type: 1,
            skin: 'layui-layer-molv', //样式类名
            closeBtn: 0, //不显示关闭按钮
            anim: 2,
            shadeClose: true, //开启遮罩关闭
            content: '内容'

        };
        return layer.open($.extend({}, defaultOptions, opt));
    }


    exporter.dialog.confirm = function (msg, success) {
        return layer.confirm(msg, {
            btn: ['确定', '取消']
        }, function (index) {
            success && success.call(this, index);
        }, function () {
        });
    };
    exporter.dialog.customConfirm = function (content, options, yes, cancel) {
        return layer.confirm(content, options, yes, cancel);
    };

    exporter.dialog.close = function (index) {
        layer.close(index);
    };


    /**
     *公共编辑弹出框
     * @param opt 公共属性
     * @param o  确定事件，初始化事件，关闭事件
     */
    exporter.dialog.edit = function (opt, o) {
        var options = $.extend({}, defaultEditDialogOpt, opt);
        var o1 = $.extend({}, defaultDialgEvent, o);
        options.buttons.ok.callback = o1.success;
        options.buttons.cancel.callback = o1.fail;
        var m = bootbox.dialog(options);
        m.init(function () {
            setTimeout(o1.init, 10);
        });
        return m;
    };


    /**
     * 自定义弹出框
     * @type {{}}
     */
    exporter.dialog.custom = function (opt) {
        return bootbox.dialog($.extend({}, opt));
    };


    /**
     *
     * @param opt
     * example:
     * bootbox.confirm({
          size: "small",
          message: "Are you sure?",
          callback: function(result){ /* result is a boolean; true = OK, false = Cancel }
     *})
     *bootbox.confirm("Are you sure?", function(result){ /* your callback code  })

     *
     */
    // exporter.dialog.confirm = function (opt) {
    //     if (arguments.length == 2) {
    //         bootbox.confirm(arguments[0], arguments[1]);
    //     } else {
    //         return bootbox.confirm($.extend({}, opt));
    //     }
    // };
    exporter.ajaxError = function (fail) {
        fail = fail || $.noop();
        return function (jqXHR, textStatus, errorThrown) {
            if (jqXHR.status === 401) {
                window.top.location.href = '/login';
            } else {
                if (fail) {
                    fail.call(this, jqXHR, textStatus, errorThrown);
                }

            }
        };
    };


    function ajaxCommon(opt, success, fail) {
        success = success || $.noop();
        fail = fail || $.noop();
        var ajaxError = exporter.ajaxError(fail);
        return $.ajax(opt).done(function (data) {
            success.call(this, data);
            // if (data && data.flag) {
            //     success.call(this, data);
            // } else {
            //     exporter.debug.info(data);
            //     exporter.dialog.alert('获取失败');
            // }
        }).fail(ajaxError);
    }


    //ajax
    exporter.ajax = function (opt, success, fail) {
        var ajaxOpt = $.extend({}, ajaxDefaultOpt, opt);
        return ajaxCommon(ajaxOpt, success, fail);
    };


    //content-type 是 application/json
    exporter.jsonAjax = function (opt, success, fail) {
        var ajaxOpt = $.extend({}, ajaxDefaultOpt, opt);
        ajaxOpt.contentType = 'application/json; charset=utf-8';
        ajaxOpt.data = JSON.stringify(ajaxOpt.data);
        return ajaxCommon(ajaxOpt, success, fail);
    };


    //validater 默认配置项
    exporter.validate = {};
    exporter.validate.default = {
        errorElement: 'div',
        errorClass: 'help-block',
        focusInvalid: false,
        ignore: "",
        highlight: function (e) {
            $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
        },

        success: function (e) {
            $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
            $(e).remove();
        },

        errorPlacement: function (error, element) {
            if (element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                var controls = element.closest('div[class*="col-"]');
                if (controls.find(':checkbox,:radio').length > 1) controls.append(error);
                else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
            }
            else if (element.is('[name=province]') || element.is('[name=city]') || element.is('[name=area]')) {
                if (element.closest('.form-group').find('.help-block').length === 0) {
                    error.insertAfter(element.parent());
                }
            }
            else if (element.is('.select2')) {
                error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
            }
            else if (element.is('.chosen-select')) {
                error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
            }
            else error.insertAfter(element.parent());
        },

        submitHandler: function (form) {
        },
        invalidHandler: function (form) {
        }
    };

    exporter.config = {
        //apiUrl: 'http://118.25.1.144:8125',
        apiUrl: 'http://localhost:8125',
        //apiUrl: 'http://192.168.23.174:8125',
        prefix: '/api/v1/admin',
        //updateReportUrl: 'http://118.25.1.144:8126/api/v1/service/addOrUpdateRpt',
        updateReportUrl: 'http://localhost:8126/api/v1/service/addOrUpdateRpt',
        getApiUrl: function (url) {
            var prefixUrl = exporter.config.apiUrl + exporter.config.prefix;
            if (url.substr(0, 1) === '/') {
                return prefixUrl + url;
            } else {
                return prefixUrl + '/' + url;
            }
        },
        enumValues: {}
    };
    var _getApiUrl, _configUrl;

    _getApiUrl = exporter.config.getApiUrl;
    exporter.config.url = {};
    _configUrl = exporter.config.url;


    _configUrl.login = _getApiUrl('login');


    /**
     * 平台管理 url
     * @type {{list: *}}
     */
    _configUrl.platform = {
        list: _getApiUrl('/searchplatforms'),
        column: _getApiUrl('/columnstyle'),
        edit: _getApiUrl('/searchsingleplatforms'),
        save: _getApiUrl('/editplatforms'),
        del: _getApiUrl('/delplatforms'),
        check: _getApiUrl('/checkPlatformName'),
        updateReport: _getApiUrl("/checkInit")
    };

    /**
     *省市区 url
     */
    _configUrl.select = {
        province: _getApiUrl('/province'),
        city: _getApiUrl('/city'),
        area: _getApiUrl('/place')
    };

    /**
     *样式管理 url
     */
    _configUrl.style = {
        list: _getApiUrl('/rolesmenu'),
        del: _getApiUrl('/delrolesmenu'),
        data: _getApiUrl('/getrolesmenu'),
        save: _getApiUrl('/editrolesmenu'),
        menu: _getApiUrl('/searchmenus'),
        check: _getApiUrl('/checkmenus')
    };

    /**
     *用户管理 url
     */
    _configUrl.user = {
        list: _getApiUrl('searchuserinfos'),
        del: _getApiUrl('deluserinfo'),
        data: _getApiUrl('getuserinfodetail'),
        save: _getApiUrl('edituserinfos'),
        menu: _getApiUrl('searchmenuforuser'),
        changeStatus: _getApiUrl('setstatusofuserinfo'),
        nameDistinct: _getApiUrl('checkusername'),
        platform: _getApiUrl('searchplatformsforuser'),
        dataArea: _getApiUrl('searchdatarangeforuser')
    };

    /**
     *日志管理
     */
    _configUrl.log = {
        list: _getApiUrl('searchuserinforforsys'),
        history: _getApiUrl('searchuserhistory'),
        downloadUser: _getApiUrl('exportexceluserhistory'),
        downloadAll: _getApiUrl('exportexcelforuser')
    };

    /**
     *数据稽核 url
     */
    _configUrl.dataAudit = {
        list: _getApiUrl('searchdataaudit'),
        data: _getApiUrl('searchdataauditbyid'),
        del: _getApiUrl('deldataauditbyids'),
        save: _getApiUrl('editdataaudit')
    };


    /**
     * 数据更新 url
     * @type {{list: *}}
     */
    _configUrl.dataUpdate = {
        list: _getApiUrl('searchschedulejob'),
        data: _getApiUrl('searchschedulejobbyid'),
        handle: _getApiUrl('processschedulejobbyids'),
        detail: _getApiUrl('searchschedulejoblog')
        // del: _getApiUrl('deldataauditbyids'),
        // save: _getApiUrl('editdataaudit')
    };

    /**
     *公共枚举
     * @private
     */
    exporter.config.enumValues = {
        platType: {
            province: {
                name: '省级',
                value: 1
            },
            city: {
                name: '市级',
                value: 2
            },
            area: {
                name: '区县级',
                value: 3
            },
            garden: {
                name: '园区级',
                value: 4
            }
        },
        platStatus: {
            forbidden: {
                name: '禁用',
                value: -2

            },
            // del: {
            //     name: '删除',
            //     value: -1
            //
            // },
            start: {
                name: '启用',
                value: 1

            },
            trial: {
                name: '试用',
                value: 2

            }
        },
        userStatus: {
            forbidden: {
                name: '禁用',
                value: -2

            },
            start: {
                name: '启用',
                value: 1

            }
        },
        auditType: {
            add: {
                name: '添加',
                value: 1

            },
            del: {
                name: '移除',
                value: 2

            }
        },
        getArray: function (_enum) {
            var k,
                r = [];
            for (k in _enum) {
                //考虑 原型链上的属性
                if (_enum.hasOwnProperty(k)) {
                    r.push(_enum[k]);
                }
            }
            return r;
        },
        getSelected: function (_enum, value) {
            var r;
            $.each(_enum, function (k, v) {
                if (v.value === value) {
                    r = _enum[k];
                    return false;
                }
            });
            return r;
        }
    };


    /**
     * 初始化 枚举类的 select 菜单
     * @param ele
     * @param _enum
     * @param emptyText
     */
    exporter.selectEnumInit = function (ele, _enum, emptyText) {
        var enumArray = exporter.config.enumValues.getArray(_enum);
        var html = ['<option value="">' + emptyText + '</option>'];
        $.each(enumArray, function (i, item) {
            html.push('<option value="' + item.value + '">' + item.name + '</option>');
        });
        ele.html(html.join(''));
    };


    /**
     * select 初始化
     * @param option
     */
    exporter.selectRemoteInit = function (option) {
        var defaultOpt = {
            ele: undefined,
            url: '',
            emptyText: '-请选择-',
            isAsync: true,
            keyId: 'id',
            valueId: 'name'
        };
        var opt = $.extend({}, defaultOpt, option);
        if (!opt.ele) {
            return;
        }
        var successEvent = function (data) {
            if (data && data.flag) {
                data = data.data;
                if (data && data.length) {
                    var html = ['<option value="">' + opt.emptyText + '</option>'];
                    $.each(data, function (i, item) {
                        html.push('<option value="' + item[opt.keyId] + '">' + item[opt.valueId] + '</option>');
                    });
                    opt.ele.html(html.join(''));
                }
            } else {
                exporter.debug.info(data);
            }
        };
        exporter.ajax({
            url: opt.url,
            type: 'get',
            async: opt.isAsync
        }, successEvent);
    };


    exporter.debug = {
        info: function (message) {
            console && console.log(message);
        },
        log: function (message) {
            console && console.log(message);
        },
        warn: function (message) {
            console && console.warn(message);
        }
    };


    if (!window.BT) {
        window.BT = {};
    }
    if (window.BT.util) {
        window.BT.util = $.extend({}, window.BT.util, exporter);
    } else {
        window.BT.util = exporter;
    }

})();


;(function () {
    $.fn.serializeObject = function () {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };
})();

/**绑定参数
 */
;(function () {
    $.fn.bindForm = function (params) {
        var me = this;
        return me.each(function () {
            var self = this;
            new FormBind({'form': $(self), 'params': params}).bind();
        });
    }

    function FormBind(opt) {
        this.form = opt.form;
        this.params = opt.params;
    }

    FormBind.prototype.bind = function () {
        var self = this;
        if (!self.params) return;
        $('input', self.form).each(function () {
            var me = this;
            if ($(me).attr('data-bind-ignore') === 'true') return true;//continue
            //var val = self.timeFormatter(self.params[me.name]);
            var val = self.params[me.name];
            if (!(val || val === 0)) {
                return true;
            }
            // if ($.isArray(val)) {
            //     return true;
            // }
            // if (typeof val === 'object') {
            //     return true;
            // }
            if (me.type == "text" || me.type == "hidden") {
                $(me).val(val);
            }
            else if (me.type == "checkbox") {
                if ($.isArray(val)) {
                    var selected = $.grep(val, function (n, i) {
                        return n.toString() === $(me).val()
                    });
                    if (selected.length === 1) {
                        $(me).prop("checked", true);
                    } else {
                        $.each(val, function (i, v) {
                            $('[value="' + v + '"]', me).prop('checked', true);

                        });
                    }
                } else {
                    $(me).prop("checked", val === "True" || val === true)
                    //$(me).prop("checked", val === "True" || val === true).click();
                }
            }
            else if ((me.type == "radio")) {
                $("input[name=" + me.name + "][value=" + val + "]").prop("checked", true);
            }
        });
        //这里也只考虑SELECT单选的情况(多选要重写)
        $('textarea,select,:password', self.form).each(function () {
            var val = self.params[this.name];
            if (val === null || val === undefined) return;
            $(this).val((self.params[this.name]));
        });
        //$('select', self.form).each(function () {
        //    var val = self.params[this.name];
        //    if (val === null) return;
        //    $(this).find("option[value='" +val.toString()+ "']").prop("selected", true);
        //});
        $('label', self.form).each(function () {
            //var val = self.timeFormatter(self.params[$(this).attr("name")]);
            $(this).text(self.params[$(this).attr("name")]);
        });
    };
    FormBind.prototype.timeFormatter = function (value) {
        if (value == null || value == "") return value;
        var date;
        if (value.toString().indexOf("\/Date(") == -1)
            return value;
        date = new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var t = y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d) + ' ';
        var hh = date.getHours();
        var mm = date.getMinutes();
        var ss = date.getSeconds();
        if (ss === 0 && hh === 0 && mm == 0) return t;
        t += (hh < 10 ? ('0' + hh) : hh) + ':' + (mm < 10 ? ('0' + mm) : mm) + ':' + (ss < 10 ? ('0' + ss) : ss);
        return t;
    }
})();

/**获取查询参数
 */
;(function () {
    $.fn.serializeObject = function () {
        var o = {};
        //var nameArray = [];
        var a = this.serializeArray();
        $.each(a, function () {
            //存在 name相同的情况
            var val = $.trim(this.value || '');
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                    //nameArray.push(this.name);//防止重复(第一次才添加)
                }
                o[this.name].push(val);

            } else {
                o[this.name] = val;
            }
        });
        // $.each(nameArray, function (i, item) {
        //     o[item] = o[item].join(',');
        // });
        return o;
    };

})();

/**原型链扩展方法
 */
;(function () {
    /**string 扩展方法  字符串格式化
     */
    String.prototype.format = function (args) {
        var result = this;
        if (arguments.length > 0) {
            if (arguments.length == 1 && typeof (args) == "object") {
                for (var key in args) {
                    if (args[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, args[key]);
                    }
                }
            }//example   var template2="我是{name}，今年{age}了";var result2=template2.format({name:"loogn",age:22});
            else {
                for (var i = 0; i < arguments.length; i++) {
                    if (arguments[i] != undefined) {
                        var reg = new RegExp("({)" + i + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }//expample var template1="我是{0}，今年{1}了"; var result1=template1.format("loogn",22);
            }
        }
        return result;
    };

    String.prototype.trim = function () {
        return $.trim(this);
    }

    String.prototype.trimEnd = function (str) {
        if (this.length == 0) return this;
        if (this.lastIndexOf(str) == this.length - 1) {
            return this.substr(0, this.length - 1);
        }
        return this;
    }

    String.prototype.toChineseNumber = function () {
        var k = new change(this);
        return k.pri_ary();
    }

    // 对Date的扩展，将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    // 例子：
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "m+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }


    var _change = {
        ary0: ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"],
        ary1: ["", "十", "百", "千"],
        ary2: ["", "万", "亿", "兆"],
        init: function (name) {
            this.name = name;
        },
        strrev: function () {
            var ary = []
            for (var i = this.name.length; i >= 0; i--) {
                ary.push(this.name[i]);
            }
            return ary.join("");
        }, //倒转字符串。
        pri_ary: function () {
            var $this = this
            var ary = this.strrev();
            var zero = ""
            var newary = ""
            var i4 = -1
            for (var i = 0; i < ary.length; i++) {
                if (i % 4 == 0) { //首先判断万级单位，每隔四个字符就让万级单位数组索引号递增
                    i4++;
                    newary = this.ary2[i4] + newary; //将万级单位存入该字符的读法中去，它肯定是放在当前字符读法的末尾，所以首先将它叠加入$r中，
                    zero = ""; //在万级单位位置的“0”肯定是不用的读的，所以设置零的读法为空

                }
                //关于0的处理与判断。
                if (ary[i] == '0') { //如果读出的字符是“0”，执行如下判断这个“0”是否读作“零”
                    switch (i % 4) {
                        case 0:
                            break;
                        //如果位置索引能被4整除，表示它所处位置是万级单位位置，这个位置的0的读法在前面就已经设置好了，所以这里直接跳过
                        case 1:
                        case 2:
                        case 3:
                            if (ary[i - 1] != '0') {
                                zero = "零"
                            }
                            ; //如果不被4整除，那么都执行这段判断代码：如果它的下一位数字（针对当前字符串来说是上一个字符，因为之前执行了反转）也是0，那么跳过，否则读作“零”
                            break;

                    }

                    newary = zero + newary;
                    zero = '';
                }
                //如果不是“0”
                else {
                    if (ary.length == 2 && i == 1 && (ary[1] == '1')) {
                        newary = this.ary1[i % 4] + newary;
                    } else {
                        newary = this.ary0[parseInt(ary[i])] + this.ary1[i % 4] + newary; //就将该当字符转换成数值型,并作为数组ary0的索引号,以得到与之对应的中文读法，其后再跟上它的的一级单位（空、十、百还是千）最后再加上前面已存入的读法内容。
                    }
                }

            }
            if (newary.indexOf("零") == 0) {
                newary = newary.substr(1)
            }//处理前面的0
            return newary;
        }
    }

    //创建class类
    function change() {
        this.init.apply(this, arguments);
    }

    change.prototype = _change;

    //创建实例
    //var k = new change("00102040");
    //alert(k.pri_ary())

})();


